package com.estore.network;

import com.estore.Product;
import com.estore.ProductService;
import java.io.*;
import java.net.*;
import java.util.List;

public class EStoreServer {
    // 创建ProductService实例
    private ProductService productService;

    public EStoreServer() {
        this.productService = new ProductService();
    }

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.start();
    }

    public void start() {
        // 创建ServerSocket并绑定到端口8888
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器已启动，监听端口 8888...");

            // 无限循环等待客户端连接
            while (true) {
                // 等待并接收客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接成功: " + clientSocket.getInetAddress());

                // 处理客户端请求
                handleClient(clientSocket);
            }
        } catch (IOException e) {
            System.err.println("服务器错误: " + e.getMessage());
        }
    }

    // 处理客户端请求的方法
    private void handleClient(Socket clientSocket) {
        try {
            // 1) 获取ObjectInputStream和ObjectOutputStream
            ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());

            // 2) 读取客户端发送的请求
            String request = (String) input.readObject();
            System.out.println("收到请求: " + request);

            // 3) 根据请求字符串调用相应方法
            Object response = null;
            if ("GET_ALL_PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                response = products;
                System.out.println("返回商品列表，数量: " + products.size());
            } else {
                response = "未知请求: " + request;
            }

            // 4) 将数据写回给客户端
            output.writeObject(response);
            output.flush();

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求时出错: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接时出错: " + e.getMessage());
            }
        }
    }
}